//
//  MNDRechargeWebViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/6/8.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDRechargeWebViewController.h"
#import "SYWebLoadingProgress.h"
#import "MNDLoginUserModel.h"

#define kRecharge_Tender   @"webreturn?sign=ucenter_tender"
#define krecharge_Continue @"webreturn?sign=ucenter_recharge"
#define Krecharge_Fail     @"webreturn?sign=recharge_failed"
/*! 忘记交易密码 */
#define kForgotPassword    @"webreturn?sign=update_account_pwd"

@interface MNDRechargeWebViewController () <UIWebViewDelegate>

@property(nonatomic, strong) UIWebView *webView;
@property (strong, nonatomic) SYWebLoadingProgress *webLoadingProgress;

@end

@implementation MNDRechargeWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialWebView];

    [self initialBackButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    if (self.presentingViewController) {
        //present方式
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            
        }];
    } else {
        //push方式
        [self.navigationController popViewControllerAnimated:YES];
    }
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"recharge_back" object:nil];
}

- (void)initialWebView {
    
    self.webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.webView];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.title = @"快捷支付";
    [self.webView loadHTMLString:self.htmlString baseURL:nil];
    
    self.webView.delegate = self;
    
    [self.view beginLoading];
}

- (NSMutableURLRequest *)addHTTPHeaderFieldWithRequest:(NSURLRequest *)request {
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    //来源加入header
    if (kDevice_iPad) {
        [mutableRequest addValue:@"iPad" forHTTPHeaderField:@"WERTYUIOP"];
    } else {
        [mutableRequest addValue:@"iPhone" forHTTPHeaderField:@"WERTYUIOP"];
    }
    
    return mutableRequest;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSMutableURLRequest *mutableRequest = [self addHTTPHeaderFieldWithRequest:request];
    request = [mutableRequest copy];
    
    NSString *absoluteUrl = request.URL.absoluteString;
    NSLog(@"absoluteUrl: %@", absoluteUrl);
    if ([absoluteUrl containsString:kRecharge_Tender]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tabBarController setSelectedIndex:1];
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        });
        
        return NO;
    }
    if ([absoluteUrl containsString:krecharge_Continue]) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
        return NO;
    }
    if ([absoluteUrl containsString:Krecharge_Fail]) {
        
        [self.navigationController popViewControllerAnimated:YES];

        return NO;
    }
    
    if ([absoluteUrl containsString:kForgotPassword]) {
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
        UINavigationController *naviVC = [storyboard instantiateViewControllerWithIdentifier:@"ResetPassworddNaviVC"];
        
        [self presentViewController:naviVC animated:YES completion:^{
            
        }];
        
        return NO;
    }
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [self.webLoadingProgress startProgressAnimation];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [self.view configBlankPage:SYBlankPageTypeNoData hasData:YES reloadButtonBlock:nil];
    //    取消长按webView上的链接弹出actionSheet的问题
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('common_header')[0].style.display='none';"];
    
    [self.webLoadingProgress completedProgressAnimation];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    
    SYBlankPageType blankType = [self.view blankPageTypeWithError:error];
    [self.view configBlankPage:blankType hasData:NO reloadButtonBlock:^(id sender) {
        [webView reload];
    }];
    [self.webLoadingProgress completedProgressAnimation];
}

- (SYWebLoadingProgress *)webLoadingProgress {
    if (!_webLoadingProgress) {
        _webLoadingProgress = [[SYWebLoadingProgress alloc] init];
        _webLoadingProgress.progressColor = kColorBlue;
        _webLoadingProgress.progressStyle = LoadingPregressType_Noraml;
    }
    
    _webLoadingProgress.frame = CGRectMake(0, 42, kScreenWidth, 2);

    [self.navigationController.navigationBar.layer addSublayer:_webLoadingProgress];
    
    return _webLoadingProgress;
}

- (void)setCookies {
    if ([MNDLoginUserModel isUserLogin]) {
        //        [self clearWebViewCookies];
        
        MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
        
        NSDictionary *dictCookieUId;
        
//        if ([userDict objectForKey:@"encode_user_code"]) {
//            dictCookieUId = @{NSHTTPCookieName: @"mobile_user_code",
//                              NSHTTPCookieValue: userDict[@"encode_user_code"],
//                              NSHTTPCookiePath: @"/",
//                              NSHTTPCookieVersion: @"0",
//                              NSHTTPCookieDomain: @".miniwangdai.com"
//                              };
//        } else {
            dictCookieUId = @{NSHTTPCookieName: @"user_code",
                              NSHTTPCookieValue: user.user_code,
                              NSHTTPCookiePath: @"/",
                              NSHTTPCookieVersion: @"0",
                              NSHTTPCookieDomain: @".miniwangdai.com"
                              };
//        }
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dictCookieUId];
        
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
